package mylab.base.foundation.orm;

import java.util.Collection;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.PageResult;
import lombok.experimental.UtilityClass;
import mylab.utils.common.SqlStringUtil;

@UtilityClass
public class EntityUtil {

    public Entity where(Class<?> entityClass) {
        return where(SqlStringUtil.camelToUnderline(entityClass.getSimpleName()));
    }

    public Entity where(String tableName) {
        return Entity.create(tableName);
    }

    public <T> Entity fromBean(T entity) {
        return Entity.parse(entity, true, true);
    }

    public <T> Collection<Entity> fromBean(Collection<T> entities) {
        return entities.stream().map(EntityUtil::fromBean).collect(Collectors.toSet());
    }

    public <T> T toBean(Entity entity, Class<T> entityClass) {
        return BeanUtil.toBean(entity, entityClass);
    }

    public <T> Collection<T> toBean(Collection<Entity> entities, Class<T> entityClass) {
        return entities.stream().map(entity -> toBean(entity, entityClass)).collect(Collectors.toSet());
    }

    public <T> PageResult<T> toBean(PageResult<Entity> entities, Class<T> entityClass) {
        PageResult<T> result = new PageResult<>(entities.getPage(), entities.getPage(), entities.getTotalPage());
        result.addAll(entities.stream().map(entity -> toBean(entity, entityClass)).collect(Collectors.toSet()));
        return result;
    }
}
